package api

import (
	"encoding/json"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/user_web/forms"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/user_web/global"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

func SendSms(c *gin.Context) {
	var req forms.SendSmsForm
	if err := c.ShouldBindJSON(&req); err != nil {
		zap.L().Error("获取请求参数失败", zap.String("method", "SendSms"), zap.Error(err))
		HandleValidatorError(c, err)
		return
	}
	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", global.ServerConfig.AliSmsInfo.ApiKey, global.ServerConfig.AliSmsInfo.ApiSecret)
	if err != nil {
		panic(err)
	}
	request := dysmsapi.CreateSendSmsRequest() //创建请求
	request.Scheme = "https"                   //请求协议
	request.PhoneNumbers = req.Phone           //接收短信的手机号码
	request.SignName = "DW生鲜"                  //短信签名名称
	request.TemplateCode = "SMS_478420857"     //短信模板ID

	code := GenerateSmsCode(6)

	par, err := json.Marshal(map[string]interface{}{ //定义短信模板参数（具体需要几个参数根据自己短信模板格式）
		"code": code,
	})
	request.TemplateParam = string(par) //将短信模板参数传入短信模板

	response, err := client.SendSms(request) //调用阿里云API发送信息
	if err != nil {                          //处理错误
		fmt.Print(err.Error())
		panic(err)
	}
	fmt.Println("response is ", *response) //控制台输出响应

	// 存储到redis中
	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})
	rdb.Set(c, req.Phone, code, time.Duration(global.ServerConfig.AliSmsInfo.Expire)*time.Second)
	c.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}

func GenerateSmsCode(n int) string {
	nums := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(nums)
	var sb strings.Builder
	for i := 0; i < n; i++ {
		fmt.Fprintf(&sb, "%d", nums[rand.Intn(r)])
	}
	return sb.String()
}
